/**
 * @file ai_chat_frame.cpp
 * @brief Implementation of AI Chat Window
 */

#include "ai_chat_frame.h"
#include <wx/msgdlg.h>
#include <wx/filedlg.h>
#include <wx/dir.h>
#include <wx/filename.h>

wxBEGIN_EVENT_TABLE(AIChatFrame, wxFrame)
    EVT_BUTTON(wxID_ANY, AIChatFrame::OnSendMessage)
    EVT_BUTTON(wxID_CLEAR, AIChatFrame::OnClearChat)
    EVT_TEXT_ENTER(wxID_ANY, AIChatFrame::OnInputEnter)
    EVT_CLOSE(AIChatFrame::OnClose)
wxEND_EVENT_TABLE()

AIChatFrame::AIChatFrame(const wxString& title)
    : wxFrame(NULL, wxID_ANY, title, wxDefaultPosition, wxSize(800, 600))
{
    CreateControls();
    SetupLayout();
    
    // Add welcome message
    AddMessage("System", "🚀 AI Communication System Started", wxColour(0, 100, 0));
    AddMessage("System", "💬 Chat Window Ready - Three Terminal Communication", wxColour(0, 100, 0));
    AddMessage("System", "👤 Human ↔ 🤖 AI ↔ 🖥️ Computer", wxColour(0, 100, 0));
    
    Centre();
}

AIChatFrame::~AIChatFrame()
{
}

void AIChatFrame::CreateControls()
{
    // Create chat display (read-only)
    m_chatDisplay = new wxTextCtrl(this, wxID_ANY, wxEmptyString, 
                                  wxDefaultPosition, wxDefaultSize, 
                                  wxTE_MULTILINE | wxTE_READONLY | wxTE_RICH2);
    m_chatDisplay->SetFont(wxFont(10, wxFONTFAMILY_MODERN, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL));
    
    // Create input text control
    m_inputText = new wxTextCtrl(this, wxID_ANY, wxEmptyString,
                                wxDefaultPosition, wxDefaultSize,
                                wxTE_PROCESS_ENTER);
    m_inputText->SetHint("Type your message here...");
    
    // Create buttons
    m_sendButton = new wxButton(this, wxID_OK, "Send");
    m_clearButton = new wxButton(this, wxID_CLEAR, "Clear");
    
    // Create terminal choice
    wxArrayString terminals;
    terminals.Add("👤 Human to AI");
    terminals.Add("🤖 AI to Computer");
    terminals.Add("💬 Direct Command");
    
    m_terminalChoice = new wxChoice(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, terminals);
    m_terminalChoice->SetSelection(0);
    
    // Create user list (simplified)
    m_userList = new wxListCtrl(this, wxID_ANY, wxDefaultPosition, wxSize(150, -1), wxLC_REPORT | wxLC_SINGLE_SEL);
    m_userList->InsertColumn(0, "Terminals", wxLIST_FORMAT_LEFT, 140);
    m_userList->InsertItem(0, "👤 Human");
    m_userList->InsertItem(1, "🤖 AI");
    m_userList->InsertItem(2, "🖥️ Computer");
}

void AIChatFrame::SetupLayout()
{
    wxBoxSizer* mainSizer = new wxBoxSizer(wxVERTICAL);
    
    // Top section with user list and chat
    wxBoxSizer* topSizer = new wxBoxSizer(wxHORIZONTAL);
    
    // Left: User list
    topSizer->Add(m_userList, 0, wxEXPAND | wxALL, 5);
    
    // Right: Chat display
    topSizer->Add(m_chatDisplay, 1, wxEXPAND | wxALL, 5);
    
    mainSizer->Add(topSizer, 1, wxEXPAND);
    
    // Bottom: Input area
    wxBoxSizer* inputSizer = new wxBoxSizer(wxHORIZONTAL);
    
    inputSizer->Add(new wxStaticText(this, wxID_ANY, "Terminal:"), 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
    inputSizer->Add(m_terminalChoice, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
    inputSizer->Add(m_inputText, 1, wxEXPAND | wxALL, 5);
    inputSizer->Add(m_sendButton, 0, wxALL, 5);
    inputSizer->Add(m_clearButton, 0, wxALL, 5);
    
    mainSizer->Add(inputSizer, 0, wxEXPAND);
    
    SetSizer(mainSizer);
    
    // Set focus to input
    m_inputText->SetFocus();
}

void AIChatFrame::AddMessage(const wxString& sender, const wxString& message, const wxColour& color)
{
    wxString timestamp = wxDateTime::Now().Format("%H:%M:%S");
    wxString formattedMessage = wxString::Format("[%s] %s: %s\n", timestamp, sender, message);
    
    // Save to history
    m_conversationHistory.push_back(formattedMessage);
    
    // Add to display with color
    m_chatDisplay->SetDefaultStyle(wxTextAttr(color));
    m_chatDisplay->AppendText(formattedMessage);
    
    // Scroll to bottom
    m_chatDisplay->ShowPosition(m_chatDisplay->GetLastPosition());
}

void AIChatFrame::OnSendMessage(wxCommandEvent& event)
{
    wxString message = m_inputText->GetValue().Trim();
    if (message.IsEmpty()) {
        return;
    }
    
    int terminal = m_terminalChoice->GetSelection();
    wxString terminalName;
    
    switch (terminal) {
        case 0: // Human to AI
            terminalName = "👤 Human";
            AddMessage(terminalName, message, wxColour(0, 0, 200));
            ProcessAIMessage(message);
            break;
            
        case 1: // AI to Computer
            terminalName = "🤖 AI";
            AddMessage(terminalName, message, wxColour(150, 0, 150));
            ExecuteComputerCommand(message);
            break;
            
        case 2: // Direct Command
            terminalName = "💬 Direct";
            AddMessage(terminalName, message, wxColour(0, 100, 0));
            ExecuteComputerCommand(message);
            break;
    }
    
    // Clear input and refocus
    m_inputText->Clear();
    m_inputText->SetFocus();
}

void AIChatFrame::OnClearChat(wxCommandEvent& event)
{
    m_chatDisplay->Clear();
    m_conversationHistory.clear();
    AddMessage("System", "Chat history cleared", wxColour(200, 0, 0));
}

void AIChatFrame::OnInputEnter(wxCommandEvent& event)
{
    OnSendMessage(event);
}

void AIChatFrame::OnClose(wxCloseEvent& event)
{
    AddMessage("System", "AI Communication System shutting down...", wxColour(200, 0, 0));
    event.Skip(); // Allow the frame to close
}

void AIChatFrame::ProcessAIMessage(const wxString& message)
{
    // Simulate AI processing
    AddMessage("🤖 AI", "Processing human message...", wxColour(150, 0, 150));
    
    wxString lowerMessage = message.Lower();
    
    if (lowerMessage.Contains("hello") || lowerMessage.Contains("hi")) {
        AddMessage("🤖 AI", "Hello! How can I assist you today?", wxColour(150, 0, 150));
    }
    else if (lowerMessage.Contains("file") || lowerMessage.Contains("read")) {
        AddMessage("🤖 AI", "I can help with file operations. Use 'list files' to see available files.", wxColour(150, 0, 150));
    }
    else if (lowerMessage.Contains("compile") || lowerMessage.Contains("build")) {
        AddMessage("🤖 AI", "I can assist with project compilation. Let me check the project files...", wxColour(150, 0, 150));
        
        // List project files
        wxArrayString cbpFiles;
        wxDir::GetAllFiles(wxGetCwd(), &cbpFiles, "*.cbp", wxDIR_FILES);
        
        if (!cbpFiles.IsEmpty()) {
            AddMessage("🤖 AI", wxString::Format("Found %d project files:", cbpFiles.size()), wxColour(150, 0, 150));
            for (const auto& file : cbpFiles) {
                AddMessage("🤖 AI", "  📁 " + wxFileName(file).GetFullName(), wxColour(150, 0, 150));
            }
        }
    }
    else if (lowerMessage.Contains("list files")) {
        AddMessage("🤖 AI", "Listing project files...", wxColour(150, 0, 150));
        
        wxArrayString files;
        wxDir::GetAllFiles(wxGetCwd(), &files, "*.cpp", wxDIR_FILES);
        wxDir::GetAllFiles(wxGetCwd(), &files, "*.h", wxDIR_FILES);
        wxDir::GetAllFiles(wxGetCwd(), &files, "*.cbp", wxDIR_FILES);
        
        AddMessage("🤖 AI", wxString::Format("Found %d files:", files.size()), wxColour(150, 0, 150));
        for (size_t i = 0; i < files.size() && i < 10; i++) {
            AddMessage("🤖 AI", "  " + wxFileName(files[i]).GetFullName(), wxColour(150, 0, 150));
        }
        if (files.size() > 10) {
            AddMessage("🤖 AI", wxString::Format("  ... and %d more files", files.size() - 10), wxColour(150, 0, 150));
        }
    }
    else if (lowerMessage.Contains("status")) {
        AddMessage("🤖 AI", "System Status:", wxColour(150, 0, 150));
        AddMessage("🤖 AI", "  🟢 AI System: Running", wxColour(150, 0, 150));
        AddMessage("🤖 AI", "  🟢 wxWidgets: 3.2.7", wxColour(150, 0, 150));
        AddMessage("🤖 AI", "  🟢 Platform: Windows", wxColour(150, 0, 150));
        AddMessage("🤖 AI", "  📁 Directory: " + wxGetCwd(), wxColour(150, 0, 150));
    }
    else if (lowerMessage.Contains("help")) {
        AddMessage("🤖 AI", "Available Commands:", wxColour(150, 0, 150));
        AddMessage("🤖 AI", "  • hello/hi - Greet the AI", wxColour(150, 0, 150));
        AddMessage("🤖 AI", "  • list files - Show project files", wxColour(150, 0, 150));
        AddMessage("🤖 AI", "  • compile/build - Project compilation", wxColour(150, 0, 150));
        AddMessage("🤖 AI", "  • status - System status", wxColour(150, 0, 150));
        AddMessage("🤖 AI", "  • help - This help message", wxColour(150, 0, 150));
    }
    else {
        AddMessage("🤖 AI", "I understand: \"" + message + "\"", wxColour(150, 0, 150));
        AddMessage("🤖 AI", "How can I help you with this?", wxColour(150, 0, 150));
    }
}

void AIChatFrame::ExecuteComputerCommand(const wxString& command)
{
    AddMessage("🖥️ Computer", "Executing: " + command, wxColour(200, 100, 0));
    
    // Simulate command execution
    if (command.Lower().Contains("compile")) {
        AddMessage("🖥️ Computer", "🔨 Starting compilation process...", wxColour(200, 100, 0));
        AddMessage("🖥️ Computer", "📦 Scanning for project files...", wxColour(200, 100, 0));
        
        wxArrayString cbpFiles;
        wxDir::GetAllFiles(wxGetCwd(), &cbpFiles, "*.cbp", wxDIR_FILES);
        
        if (!cbpFiles.IsEmpty()) {
            AddMessage("🖥️ Computer", "✅ Found " + wxString::Format("%d", cbpFiles.size()) + " project files", wxColour(200, 100, 0));
            for (const auto& file : cbpFiles) {
                AddMessage("🖥️ Computer", "  Processing: " + wxFileName(file).GetFullName(), wxColour(200, 100, 0));
            }
        }
        
        AddMessage("🖥️ Computer", "🎉 Compilation simulation completed!", wxColour(200, 100, 0));
    }
    else {
        AddMessage("🖥️ Computer", "✅ Command executed successfully", wxColour(200, 100, 0));
        AddMessage("🖥️ Computer", "📊 Result: Simulated execution of '" + command + "'", wxColour(200, 100, 0));
    }
}

// Application implementation
bool AIChatApp::OnInit()
{
    if (!wxApp::OnInit()) {
        return false;
    }
    
    m_frame = new AIChatFrame("AI Communication System - Chat Window");
    m_frame->Show(true);
    
    return true;
}

int AIChatApp::OnExit()
{
    return wxApp::OnExit();
}

wxIMPLEMENT_APP(AIChatApp);
